package com.dh.convert.rule.function;

import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.type.AviatorObject;
import com.googlecode.aviator.runtime.type.AviatorRuntimeJavaType;

import java.math.BigDecimal;
import java.util.Map;

/**
 * @fileName: BigDecimalFunction.java
 * @author: WeiHui
 * @date: 2018/11/15 21:28
 * @version: v1.0.0
 * @since JDK 1.8
 */
public class BigDecimalFunction extends AbstractFunction {

	@Override
	public String getName() {
		return "BigDecimal";
	}

	@Override
	public AviatorObject call(Map<String, Object> env, AviatorObject arg1) {
		switch (arg1.getAviatorType()) {
			case JavaType:
				Object obj = arg1.getValue(env);
				if (obj instanceof Number) {
					return new AviatorRuntimeJavaType((new BigDecimal((Double) obj)));
				} else if (obj instanceof String) {
					return new AviatorRuntimeJavaType(new BigDecimal((String) obj));
				} else if (obj instanceof Character) {
					return new AviatorRuntimeJavaType(new BigDecimal(String.valueOf(obj)));
				} else {
					throw new ClassCastException("Could not cast " + obj.getClass().getName() + " to double");
				}
			case String:
				return new AviatorRuntimeJavaType(new BigDecimal((String) arg1.getValue(env)));
			case Long:
				return new AviatorRuntimeJavaType(new BigDecimal((Long) arg1.getValue(env)));
			case Double:
				return new AviatorRuntimeJavaType(new BigDecimal((Double) arg1.getValue(env)));
			default:
				throw new ClassCastException("Could not cast " + arg1 + " to double");
		}
	}
}
